package com.huluobo.lc.ppjoke_jetpack.ui;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.DataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

/**
 * @author Lc
 * @description: 功能:所有ViewModel请求数据时的基准类,配置PagedList,所有的LiveData,暴露方法
 * @date :2020/7/20 9:32
 */
public abstract class AbsViewModel<T> extends ViewModel {
    private DataSource dataSource;
    private LiveData<PagedList<T>> liveData;

    private MutableLiveData<Boolean> boundaryPageData = new MutableLiveData<>();

    public AbsViewModel() {
        PagedList.Config config = new PagedList.Config.Builder().setPageSize(10)//每次分页加载的数量
                .setInitialLoadSizeHint(12)//初始化时加载的数量
//        .setMaxSize(100)//设置最大的数量,国内一般不调用
//        .setEnablePlaceholders(false)//当剩余的item数量不足10个的时候,启用占位符
//        .setPrefetchDistance()//当初始化10条时,继续自动加载下面的10条
                .build();

        liveData = new LivePagedListBuilder(factory, config).setInitialLoadKey(0)
                //初始化时传入的一个key
//        .setFetchExecutor()//添加一个线程池,一般不会调用,在PageList中会有默认的线程池
                .setBoundaryCallback(callback).build();
    }

    public LiveData<PagedList<T>> getPageData() {
        return liveData;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public MutableLiveData<Boolean> getBoundaryPageData() {
        return boundaryPageData;
    }

    PagedList.BoundaryCallback callback = new PagedList.BoundaryCallback() {
        @Override
        public void onZeroItemsLoaded() {
            boundaryPageData.postValue(false);
        }

        @Override
        public void onItemAtFrontLoaded(@NonNull Object itemAtFront) {
            boundaryPageData.postValue(true);
        }

        @Override
        public void onItemAtEndLoaded(@NonNull Object itemAtEnd) {
            super.onItemAtEndLoaded(itemAtEnd);
        }
    };

    DataSource.Factory factory = new DataSource.Factory() {
        @NonNull
        @Override
        public DataSource create() {
            dataSource = createDataSource();
            return dataSource;
        }
    };

    public abstract DataSource createDataSource();
}
